package com.app.Network;

import java.util.Iterator;

import com.app.Activity.frmBieuQuyetMoiRoiNhom;
import com.app.Activity.frmPhuActivity;
import com.app.Activity.trucActivity;
import com.app.Controller.ActivityController;
import com.app.Controller.NetworkController;
import com.app.Controller.ReadWriteFileController;
import com.app.DTO.AccountDTO;
import com.app.DTO.RoleDTO;
import android.os.Handler;
import android.util.Log;
import it.unipr.ce.dsg.s2p.org.json.JSONException;
import it.unipr.ce.dsg.s2p.org.json.JSONObject;
import it.unipr.ce.dsg.s2p.peer.Peer;
import it.unipr.ce.dsg.s2p.peer.PeerDescriptor;
import it.unipr.ce.dsg.s2p.sip.Address;

public class NetworkLayer extends Peer {
	private Handler hander = new Handler();
	public AccountDTO account = null;

	public AccountDTO getAccount() {
		return this.account;
	}

	public PeerDescriptor getPeerDescriptor() {
		return this.peerDescriptor;
	}

	public NetworkLayer(String pathConfig, String key, String peerName,
			int peerPort, AccountDTO account) {
		super(pathConfig, key, peerName, peerPort);
		this.account = account;
	}

	@Override
	protected void onDeliveryMsgFailure(String arg0, Address arg1, String arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDeliveryMsgSuccess(String arg0, Address arg1, String arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onReceivedJSONMsg(JSONObject peerMsg, Address sender) {
		JSONObject params = null;
		Log.d("Phu", "onReceivedJSONMsg");
		try {
			params = peerMsg.getJSONObject("payload").getJSONObject("params");
		} catch (JSONException e) {

			e.printStackTrace();
			Log.d("Loi", "Lỗi onReceivedJSONMsg try 1");
		}
		try {
			String type = (String) peerMsg.get("type");
			Log.d("Phu", "type: " + type);
//===============truc====================================
			//cam noi
			if (type.equals(Protocol.STOP_TALKING_ONE_MEMBER)) {
				
				account.getRule().get(1).setSend(false);
				Iterator<String> listKey=params.keys();
				String key;
				int time=0;
				while(listKey.hasNext()){
					Log.d("Phu","vao while");
					key=listKey.next();
					String s = null;
					try {
						s = params.get(key).toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(key.equals("TimeStopTalk")){
						time=Integer.parseInt(s);
					}
					
				}
				Log.d("Phu","moi sua: Send "+account.getRule().get(1).getSend());
				String s=Protocol.STOP_TALKING_MESSAGE+ " trong vòng "+time+" giây. Vui lòng chờ.";
				NetworkController.ShowMessageNotice(s);
				
			}//tao lao
			else if(type.equals(Protocol.HELLO)){
				NetworkController.ShowMessageNotice("Da nhan hello");
			}
			//cho noi
			else if(type.equals(Protocol.ACCEPT_TALKING_ONE_MEMBER)){
				account.getRule().get(1).setSend(true);
				Log.d("Phu","Da sua lai wuyen noi"+ account.getRule().get(0).getSend());
				NetworkController.ShowMessageNotice(Protocol.ACCEPT_TALKING_MESSAGE);
			}//chat
			else if(type.equals(Protocol.CHAT_MESSAGE))
			{
				String key;
				if(account.getRule().get(0).getReceive())
				{
					Iterator<String> listKey=params.keys();
					while(listKey.hasNext()){
						key=listKey.next();
						String s = null;
						try {
							s = params.get(key).toString();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if(key.equals("Content_Chat")){
							NetworkController.ShowMessageChat(s,sender.getURL());
							Log.d("Phu","Da show noi dung chat nhan dc");
						}
					}
				}
				else
				{
					Log.d("Phu","gui phan hoi ko chat net layer");
					NetworkController.ShowMessageNotice("ban ko co quyen nhan tin nhan chat");
					NetworkController.GuiPhanHoiKhongCoQuyenChat(sender);
				}
			}//ko co quyen nhan tin nhan chat
			else if(type.equals(Protocol.CHAT_FEDBACK_NON_RULE)){
				NetworkController.ShowMessageNotice("Doi phuong ko co quyen nhan tin nhan chat");
			}//nhan tin nhan yeu cau bieu quyet moi nguoi khac ra khoi nhom
			else if(type.equals(Protocol.KICK_MEMBER_OUT_MESSAGE)){
				
				Log.d("Phu","vao nhan vote");
				frmBieuQuyetMoiRoiNhom.senderKick=sender;
				//NetworkController.ShowMessageNotice("da nhan dc tin nhan Kick");
				//ActivityController.ShowMessage("nhan dc");
				String key;
				int time=0;
				String ipBeingKick="";
				String ip=getAddressPeer();
				Log.d("Phu","my ip "+ip);
				Iterator<String> listKey=params.keys();
				
				while(listKey.hasNext()){
					Log.d("Phu","vao while");
					key=listKey.next();
					String s = null;
					try {
						s = params.get(key).toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(key.equals("Time")){
						Log.d("Phu","key = time");
						Log.d("Phu","s ="+s);
						time=Integer.parseInt(s);
						Log.d("Phu","time="+time);
					}
					if(key.equals("IPBeingKick")){
						Log.d("Phu","key = being kick ip");
						ipBeingKick=s;
						Log.d("Phu","being kick ip="+ipBeingKick);
					}
				}
				Log.d("Phu","ra khoi while");
				
				//NetworkController.SetTimeKick(time);
				frmBieuQuyetMoiRoiNhom.timeVoteKick=time;
				//có viết hàm thông qua các class controller va activitycontroller nhung ko thanh cong nen gan truc tiep
				Log.d("Phu","settime kick");
				Log.d("Phu","time to vote = "+time);
				if(ip.equals(ipBeingKick)==false){
					Log.d("Phu","ko khop ip trong send vote");
					NetworkController.DislayVoteKickMember();
				}			
				else{
					Log.d("Phu","khop ip trong send vote");
					NetworkController.ShowMessageNotice("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
					//phai phong truong hop no nhan duoc thong bao nay tu nhien roi khoi nhom.ko cho quyet dinh.
					Log.d("Phu","Da show thong bao ");
				}
				
			}//nhan duoc phan hoi moi nguoi khac ra khoi nhom
			else if(type.equals(Protocol.KICK_MEMBER_OUT_FEDBACK))
			{
				Log.d("Phu","vao fan hoi vote");
				NetworkController.ShowMessageNotice("da nhan dc tin nhan phan hoi Kick");
				String key;
				
				Iterator<String> listKey=params.keys();
				while(listKey.hasNext()){
					key=listKey.next();
					String s = null;
					try {
						s = params.get(key).toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(key.equals("VOTE")){
						Log.d("Phu","lay vote");
						if(s.equals("1")){
							trucActivity.yesVote.add(1);
						}
						else if(s.equals("0"))
						{
							trucActivity.noVote.add(1);
						}
					}
				}
			}//nhan dc ket qua cuoi dung
			else if(type.equals(Protocol.KICK_MEMBER_OUT_RESULT)){
				NetworkController.ShowMessageNotice("da nhan dc ket qua Kick");
				String key;
				int kq=-1;
				Iterator<String> listKey=params.keys();
				Address myIP=getAddress();
				String ipBeingKick="";
				while(listKey.hasNext()){
					key=listKey.next();
					String s = null;
					try {
						s = params.get(key).toString();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
					if(key.equals("Result")){
						Log.d("Phu","lay ket qua cuoi cung");
						if(s.equals("1")){
							//NetworkController.ShowMessageNotice("Thành viên trên đã bị mời khỏi nhóm");
							kq=1;
						}
						else if(s.equals("0"))
						{
							kq=0;
							//NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
						}
						Log.d("Phu","ket qua cuoi cung = "+s);
					}
					
					if(key.equals("BeingKick")){
						Log.d("Phu","lay ip bi kick result");
						Log.d("Phu","ip bi kick result : "+s);
						ipBeingKick=s;
					//	Log.d("Phu","My ip result : "+myIP.getURL());
						
					}					
				}
				if(ipBeingKick.equals(myIP.getURL())){
					Log.d("Phu","khop ip bi kick result");
					if(kq==1){
						Log.d("Phu","kq bi kick result =1 ");
						NetworkController.ShowMessageNotice("Bạn đã bị mời khỏi nhóm.");
						//xoa nguoi nay khoi danh sach nhom
					//	NetworkController.CloseActivity();
					}
					else{
						Log.d("Phu","kq bi kick result =0 ");
						NetworkController.ShowMessageNotice("Các thành viên mời bạn rời khỏi nhóm đã thất bại.");
					}
				}
				else
				{
					Log.d("Phu","khop ip bi kick result");
					if(kq==1){
						Log.d("Phu","kq bi kick result =1 ");
						NetworkController.ShowMessageNotice("Thành viên trên đã bị mời khỏi nhóm.");
					}
					else{
						Log.d("Phu","kq bi kick result =0 ");
						NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
					}
					
				}
				
			}
			//==============================================truc========================================
			//Đồng ý vào nhóm
			else if(type.equals(Protocol.GROUP_INVITE_REPLY_YES)){
				Log.d("nhan","nhan dc: "+type);
				
				if(nhomDaFull()){
					Log.d("phu","Nhom da day - ko cho vao nhom");					
					NetworkController.sendKhongChoVaoNhom(sender);
				}
				else{
					Log.d("phu","Cho vao nhom roi day");
					Log.d("phu","host: "+sender.getHost());
					hander.post(frmPhuActivity.raUpdateNguoiTrongNhom);
					NetworkController.sendChoVaoNhom(sender);
				}
			}
			//Không đc vào nhóm
			else if(type.equals(Protocol.GROUP_INVITE_NO)){
				Log.d("phu","no ko cho may vao nhom");
				hander.post(frmPhuActivity.raKhongDuocVaoNhom);
			}
			//Đã đc vào nhóm
			else  if(type.equals(Protocol.GROUP_INVITE_YES)){
				Log.d("phu","may da vao nhom vao nhom");
				hander.post(frmPhuActivity.raDaVaoNhom);
			}
			//Set role
			else if(type.equals(Protocol.SET_ROLE)){
				String data="";
				Iterator<String> iter = params.keys();
				while(iter.hasNext()){			
					String key = iter.next();
					Log.d("Phu","key:"+key);
					if(key.equals("DATA")){
						try {
							data = params.getString(key);
							Log.d("Phu","data:"+data);
							break;
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}					

					}
				}
				final String s=data;
				hander.post(new Runnable() {
					
					@Override
					public void run() {
						//NetworkController._peer.account.set/
						String path=ReadWriteFileController.MY_ROLE_PATH;
						ReadWriteFileController.writeRole(path, RoleDTO.parseList(s, ReadWriteFileController.RULE_BASE_PATH));
						NetworkController.resetRole();
						
					}
				});
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.d("Loi", "Loi trong ham nhận message");
		}
		
	}

	public String getAddressPeer() {

		return getAddress().getURL();
	}

	public String getContactAddressPeer() {

		return peerDescriptor.getContactAddress();
	}

	private boolean nhomDaFull() {
		return true;
	}
}
